extends Node2D

@export var damage = 15
@export var attack_cooldown = 0.5  # 攻击冷却时间（秒）
@export var rotation_speed = 3.0  # 旋转速度（弧度/秒）
@export var orbit_radius = 100.0  # 绕玩家旋转的半径
@export var axe_count = 1  # 斧头数量
@export var axe_size = 1.0  # 斧头大小缩放

@onready var attack_timer = $AttackTimer
@onready var animation_player = $AnimationPlayer

var owner_player = null  # 持有此武器的玩家引用
var axe_instances = []  # 存储所有斧头实例
var current_angle = 0.0  # 当前旋转角度

func _ready():
	attack_timer.wait_time = attack_cooldown
	attack_timer.one_shot = false  # 设置为重复
	attack_timer.start()
	
	# 确保有动画播放器
	if not animation_player:
		print("WARNING: SpinningAxe missing AnimationPlayer!")
	
	# 初始化斧头
	spawn_axes()

func _process(delta):
	# 更新斧头位置
	update_axes_position(delta)

func set_owner_player(player_node):
	owner_player = player_node

func spawn_axes():
	# 清除现有斧头
	for axe in axe_instances:
		if is_instance_valid(axe):
			axe.queue_free()
	axe_instances.clear()
	
	# 创建新斧头
	var angle_step = 2 * PI / axe_count
	for i in range(axe_count):
		var axe = preload("res://AxeProjectile.tscn").instantiate()
		get_tree().get_root().add_child(axe)
		
		# 设置斧头属性
		axe.damage = damage
		axe.scale = Vector2(axe_size, axe_size)
		
		# 计算初始位置
		var angle = current_angle + i * angle_step
		var offset = Vector2(cos(angle), sin(angle)) * orbit_radius
		axe.global_position = global_position + offset
		
		# 存储斧头实例
		axe_instances.append(axe)

func update_axes_position(delta):
	if not owner_player:
		return
	
	# 更新旋转角度
	current_angle += rotation_speed * delta
	if current_angle > 2 * PI:
		current_angle -= 2 * PI
	
	# 更新每个斧头的位置
	var angle_step = 2 * PI / axe_count
	for i in range(axe_instances.size()):
		var axe = axe_instances[i]
		if is_instance_valid(axe):
			var angle = current_angle + i * angle_step
			var offset = Vector2(cos(angle), sin(angle)) * orbit_radius
			axe.global_position = owner_player.global_position + offset
			
			# 检测与敌人的碰撞
			check_axe_collision(axe)

func check_axe_collision(axe):
	# 获取场景树中"enemies"组内的所有敌人
	var enemies = get_tree().get_nodes_in_group("enemies")
	
	for enemy in enemies:
		# 确保敌人有效且未被标记为删除
		if is_instance_valid(enemy) and enemy.has_method("take_damage"):
			# 简单的距离检测（可以改进为使用Area2D和信号）
			var distance = axe.global_position.distance_to(enemy.global_position)
			if distance < 30 * axe_size:  # 假设碰撞半径为30像素乘以缩放
				# 应用暴击（如果玩家有暴击属性）
				var actual_damage = damage
				if owner_player and owner_player.has_method("get_crit_info"):
					var crit_info = owner_player.get_crit_info()
					if randf() < crit_info.chance:
						actual_damage *= crit_info.multiplier
						# 可以添加暴击视觉效果
				
				# 对敌人造成伤害
				enemy.take_damage(actual_damage)
				
				# 播放攻击动画（如果有）
				if animation_player and animation_player.has_animation("hit"):
					animation_player.play("hit")
				
				print(name, " 斧头击中 ", enemy.name, " 造成 ", actual_damage, " 伤害")

func _on_attack_timer_timeout():
	# 这个计时器用于定期检查碰撞，但主要逻辑在_process中
	pass

# 由Player的apply_upgrade函数调用
func upgrade_stat(stat_name, value):
	match stat_name:
		"damage":
			damage += value
			print(name, " 伤害提升至: ", damage)
			# 更新所有斧头的伤害
			for axe in axe_instances:
				if is_instance_valid(axe):
					axe.damage = damage
		"speed":  # 增加旋转速度
			rotation_speed += value
			print(name, " 旋转速度增加至: ", rotation_speed)
		"count":  # 增加斧头数量
			axe_count += value
			print(name, " 斧头数量增加至: ", axe_count)
			# 重新生成斧头
			spawn_axes()
		"size":  # 增加斧头大小
			axe_size += value
			print(name, " 斧头大小增加至: ", axe_size)
			# 更新所有斧头的大小
			for axe in axe_instances:
				if is_instance_valid(axe):
					axe.scale = Vector2(axe_size, axe_size)
		"radius":  # 增加旋转半径
			orbit_radius += value
			print(name, " 旋转半径增加至: ", orbit_radius)
		_:
			print("未知属性升级: ", stat_name)
